package com.sm.tool.utils;

/**
 * 
 * IP工具类
 *
 * @author liqitian
 * @createDate 2018-12-27
 */
public class IpAddressUtil {

    private static final String IP_PATTERN = "^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\."
            +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
            +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)\\."
            +"(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|\\d)$";

    private static final String LOCALHOST = "127.0.0.1";
    private static final String UNKNOWN = "unknown";
    
    
    /**
     * 验证IP合法性
     * @param ip
     * @return
     */
    public static boolean validateIP(String ip){
        return ip.matches(IP_PATTERN);
    }

    public static boolean inLAN(javax.servlet.http.HttpServletRequest request) {
        String ip = getRemoteHost(request);
        return inLAN(ip);
    }

    public static boolean inLAN(String ipAddress){
        if (LOCALHOST.equals(ipAddress)) {
            return true;
        }
        byte[] addr = ip2Byte(ipAddress);
        final byte b0 = addr[0];
        final byte b1 = addr[1];
        //10.x.x.x/8
        final byte section1 = 0x0A;
        //172.16.x.x/12
        final byte section2 = (byte) 0xAC;
        final byte section3 = (byte) 0x10;
        final byte section4 = (byte) 0x1F;
        //192.168.x.x/16
        final byte section5 = (byte) 0xC0;
        final byte section6 = (byte) 0xA8;
        switch (b0) {
            case section1:
                return true;
            case section2:
                if (b1 >= section3 && b1 <= section4) {
                    return true;
                }
            case section5:
                switch (b1) {
                    case section6:
                        return true;
                    default:
                    	return false;
                }
            default:
                return false;

        }
    }

    private static byte[] ip2Byte(String ip) {
        byte[] addr = new byte[4];
        String[] nums = ip.split("\\.");
        for (int i = 0; i < nums.length; i++) {
            addr[i] = (byte)Integer.parseInt(nums[i]);
        }
        return addr;
    }

    public static String getRemoteHost(javax.servlet.http.HttpServletRequest request){
        String ip = request.getHeader("x-forwarded-for");
        if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)){
            ip = request.getHeader("Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)){
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if(ip == null || ip.length() == 0 || UNKNOWN.equalsIgnoreCase(ip)){
            ip = request.getRemoteAddr();
        }
        return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : ip;
    }

}
